import React, {useEffect,useRef} from 'react';
import {App, Button, Card, Form, Input, InputNumber, Select, Switch} from "antd";
import {Link, useNavigate} from "react-router-dom";
import TextArea from "antd/es/input/TextArea";
import {SecurityPath} from "type/SecurityPath";
import LogFactory from "log/LogFactory";
import {requestGet} from "util/request";
import {DefaultOptionType} from "rc-select/lib/Select";
import {useAppDispatch} from "../../../redux/hook" ;
import {fetchAddData} from "../../../redux/reducer/pathReducer";

const log = LogFactory.getLog("PathAddComponent");
const PathAddComponent = () => {

    const { message } = App.useApp();
    const dispatch = useAppDispatch() ;
    const navigate = useNavigate() ;
    const [form] = Form.useForm<SecurityPath>() ;
    const pathParentRef = useRef<SecurityPath[]>([]) ;

    const [option , setOption] = React.useState<DefaultOptionType[]>([]) ;
    useEffect(() => {
        requestGet<SecurityPath[]>("/manager/security-path/list/parent")
            .then(res => {
              if (res.success){
                  // log.debug("parent-path-list: " , res) ;
                  pathParentRef.current = res.data ;
                  let data = res.data.map((item,index) => ({
                      label: item.explain,
                      value: item.id
                  }));
                  data.push({label: "主路径根节点",value: 0}) ;
                  setOption(data) ;
              }
            });
    },[]) ;
    const selectOnChange = (value: number) => {
        log.debug("select-on-change: " , value) ;
        pathParentRef.current.forEach(e => {
            if (e.id === value){
                form.setFieldsValue({
                    pattern: e.pattern.replaceAll("*",""),
                }) ;
                return;
            }
            if (e.id === 0){
                form.setFieldsValue({
                    pattern: "/",
                }) ;
                return ;
            }
        });
    };
    const initialValues: Partial<SecurityPath> = {
        method: "GET",
        last: true,
        order: 1,
        parentId: 0,
        pattern: "/"
    } ;
    const onFinish = async (values: SecurityPath) => {
        // log.debug("提交添加路径表单",values) ;
        let res = await dispatch(fetchAddData(values)).unwrap().then(res => res) ;
        if (res > 0) {
            log.debug("添加路径数据成功") ;
            message.success("添加路径数据成功") ;
            navigate("",{replace: true}) ;
        }else {
            log.debug("添加路径数据失败") ;
            message.info("添加路径数据失败") ;
        }
    };

    return (
        <Card
            title={"添加路径数据"}
            extra={ <Link key={"path-list"} to={""}>路径列表</Link> }
        >
            <Form<SecurityPath>
                form={form}
                layout={"horizontal"}
                // labelWrap={false}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 12 }}
                onFinish={ onFinish }
                initialValues={initialValues}
            >
                <Form.Item<SecurityPath> label="父路径" name={"parentId"}>
                    <Select
                        loading={false}
                        options={option}
                        maxLength={3}
                        onChange={ selectOnChange }
                    />
                </Form.Item>
                <Form.Item<SecurityPath> label="路径模式" name={"pattern"}>
                    <Input />
                </Form.Item>
                <Form.Item<SecurityPath> label="路径描述" name={"explain"}>
                    <Input />
                </Form.Item>
                <Form.Item<SecurityPath> label="子路径" name={"last"}>
                    <Switch />
                </Form.Item>
                <Form.Item<SecurityPath> label="请求方法" name={"method"}>
                    <Select>
                        <Select.Option value="GET">GET 请求</Select.Option>
                        <Select.Option value="POST">POST 请求</Select.Option>
                        <Select.Option value="PUT">PUT 请求</Select.Option>
                        <Select.Option value="DELETE">DELETE 请求</Select.Option>
                        <Select.Option value="ANY">任何请求</Select.Option>
                        <Select.Option value="DEFAULT">默认请求</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item<SecurityPath> name="order" label="数据排序">
                    <InputNumber min={0}/>
                </Form.Item>
                <Form.Item<SecurityPath> name={"remark"} label="备注信息">
                    <TextArea rows={5}/>
                </Form.Item>
                <Form.Item wrapperCol={{offset: 8,span: 16}}>
                    <Button type="primary" htmlType="submit">添加</Button>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default PathAddComponent;